from django.shortcuts import render, get_object_or_404, redirect
from django.http import HttpResponseRedirect
from django.urls import reverse
from .models import Question, Choice
import datetime

def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    return render(request, 'polls/index.html', {'latest_question_list': latest_question_list})

def add_question(request):
    if request.method == 'POST':
        question_text = request.POST['question_text']
        new_question = Question(question_text=question_text, pub_date=datetime.datetime.now())
        new_question.save()
        
        # 处理多个选项
        choice_texts = request.POST.getlist('choice_text')
        for choice_text in choice_texts:
            if choice_text:
                Choice.objects.create(question=new_question, choice_text=choice_text)
        
        return HttpResponseRedirect(reverse('polls:index'))
    
    return render(request, 'polls/add_question.html')

def detail(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/detail.html', {'question': question})

def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        return render(request, 'polls/detail.html', {
            'question': question,
            'error_message': "请选择一个选项",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))

def results(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/results.html', {'question': question})